import React from 'react';
import {
    View,
    Text,
    ScrollView,
    TouchableOpacity, Image,
    StyleSheet
} from 'react-native';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
import ImagePicker from 'react-native-image-crop-picker';
import {
    InputItem,
    List,
} from '@ant-design/react-native';
import Dict from '../../../common/Dict';
import FormItem from "../../../common/components/FormItem";
import FormRadioItem from "../../../common/components/FormRadioItem";
import GlobalStyles from "../../../common/styles/GlobalStyles";
import PickerViewModalCas from '../../../common/components/PickerViewModalCas';
import PersonalDialog from '../../dialogComponents/PersonalDialog'
import FontAwesome from "react-native-vector-icons/FontAwesome";
import ToastUtil from "../../../utils/ToastUtil";
import {BASE_URL} from '../../../common/BASE_URL';
import TextInputItem from "../../../common/components/inputItem";

import AuthUtil from '../../../common/AuthUtils';

//百度Ai识别接口
const BaiDuImgAnalysis =  BASE_URL.apiBaseUrl + '/app/baidu/getIdCardData'


export default class PersonalInfoForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            sexDict: [],
            idTypeDict: [],
            userInfoVo: {
                contactName:'',
                contactGender:'',
                contactGenderLabel : '',
                contactIdType: '',
                contactIdTypeLabel: '',
                contactIdNumber: '',
                contactPhone:'',
                contactEmail:'',
                contactAddress:'',
                unitName:'',
                position: '',
            },
            imgList: []//存放照片
        };
    }

        //
    async componentDidMount(){
        const gender = await Dict.getDict('dict_gender')
        const idType = await Dict.getDict('id_type')
        

        if(this.state.userInfoVo.contactIdType === '' && idType.length > 0){
            this.state.userInfoVo.contactIdType = idType[0].value
            this.state.userInfoVo.contactIdTypeLabel = idType[0].label
        }
        if(this.state.userInfoVo.contactGender === '' && gender.length > 0){
            this.state.userInfoVo.contactGender = gender[0].value
            this.state.userInfoVo.contactGenderLabel = gender[0].label
        }

        this.setState({
            sexDict: gender,
            idTypeDict: idType,
        })
    }

    validateForm() {
        const info = this.state.userInfoVo
        if(!info.contactName || !info.contactName.trim()){
            ToastUtil.info('请输入姓名')
            return false
        }
        return true
    }

    _changeFormData(key,value,type){
        let update = {};
        if(type === 'radio'){
            console.log(value)
            update = {
                [key+'Label']: value.label,
                [key]: value.value
            }
        }else if(type === 'select'){
            update = {
                [key]: value.value[0],
                [key+'Label']: value.label[0],
            };
        }else{
            update = { [key]: value};
        }
        const data = Object.assign({}, this.state.userInfoVo, update);
        this.setState({
            userInfoVo: data,
        });
        this.props.onChange && this.props.onChange(data)
    }

    _BaiDuAi(){
        let options={
            mediaType:'photo',
            maxWidth:400,
            maxHeight:300,
            videoQuality:'',
            durationLimit:120,
            quality:1,
            cameraType:'back',
            includeBase64:false,
            saveToPhotos:true,
            selectionLimit:1,
        }
        let that=this
        launchCamera(options, (res)=>{
            if(res.assets){
                that.updateImg(res.assets)
            }
        });
    }

    updateImg(imgAry){
        let formData = new FormData()
        for(var i = 0;i<imgAry.length;i++){
            let file = {uri: imgAry[i].uri, type: imgAry[i].type, name: '身份证照片'};   //这里的key(uri和type和name)不能改变,
            formData.append("file",file);   //这里的files就是后台需要的key
        }
        let that=this
        AuthUtil.getAuthParam().then((authHeader)=>{
        fetch(BaiDuImgAnalysis, {
            headers: {
                'Content-Type': 'multipart/form-data',
                ...authHeader,
            },
            method: 'POST',
            timeout: 4000,
            body:formData,
            }).then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Network response was not ok.');
            })
            .then((res) => {
                let infoObj=res.words_result
                //   let infoArr=['姓名','民族','住址','公民身份号码','出生','性别']
                    let sex=1
                    console.log("infoObj")
                    console.log(infoObj)
                    console.log(infoObj['性别'])
                    if(infoObj['性别'].words=='男'){
                        sex=1
                    }else{
                        sex=0
                    }
                    console.log("infoObj")
                    console.log(infoObj)
                    let data={
                        contactName:infoObj['姓名'].words,
                        contactGender:sex,
                        contactIdNumber:infoObj['公民身份号码'].words,
                        contactAddress:infoObj['住址'].words,
                    }
                    let obj=Object.assign({}, that.state.userInfoVo,data)
                    that.setState({
                        userInfoVo:obj
                    })
            })
          })
    }

    render() {
        const userInfoVo = this.state.userInfoVo
        return (
            <View style={[GlobalStyles.innerTabPanel,{flexDirection: 'column',flex: 1}]}>
                {this._renderHeaderBtns()}
                {this._renderHeaderBtns2()}
                <ScrollView
                    style={{flex: 1}}
                    automaticallyAdjustContentInsets={false}
                    showsHorizontalScrollIndicator={false}
                    showsVerticalScrollIndicator={false}>
                    <List>
                        {/* <InputItem
                            value={userInfoVo.contactName}
                            maxLength={50}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('contactName',value)}
                            placeholder="请输入姓名">
                            <View style={GlobalStyles.formRow}>
                                <Text style={{fontSize:14,width:100}}>姓名</Text>
                                <FontAwesome name={'asterisk'} color={'red'} size={8} style={GlobalStyles.formRowRequire}/>
                            </View>
                        </InputItem> */}
                        <TextInputItem
                            label={"姓名"}
                            placeholder={"请输入姓名"}
                            maxLength={50}
                            value={userInfoVo.contactName}
                            labelWidth={100}
                            isMust={true}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{contactName:value})
                                this.setState({
                                    userInfoVo:data
                                })
                                this._changeFormData('contactName',value)
                            }}
                        />
                        
                        <FormRadioItem
                            label={'性别'}
                            checked={[userInfoVo.contactGender]}
                            data={this.state.sexDict}
                            onChange={(value) => this._changeFormData('contactGender',value, 'radio')}
                        />
                        <FormItem
                            label={'证件类型'}
                            placeholder={'请选择类型'}
                            maxLength={50}
                            value={userInfoVo.contactIdTypeLabel}
                            onClick={() => {
                                this.refs.typePicker.show();
                            }}
                        />

                        {/* <InputItem
                            value={userInfoVo.contactIdNumber}
                            type={'number'}
                            labelNumber={6}
                            maxLength={50}
                            onChange={(value) => this._changeFormData('contactIdNumber',value)}
                            placeholder="请输入证件号码">
                            <Text style={{fontSize:14,width:100}}>证件号码</Text>
                        </InputItem> */}
                        <TextInputItem
                            label={"证件号码"}
                            placeholder={"请输入证件号码"}
                            maxLength={50}
                            onlyNum={true}
                            value={userInfoVo.contactIdNumber}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{contactIdNumber:value})
                                this.setState({
                                    contactIdNumber:data
                                })
                                this._changeFormData('contactIdNumber',value)
                            }}
                        />


                        {/* <InputItem
                            value={userInfoVo.contactPhone}
                            type={'phone'}
                            maxLength={50}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('contactPhone',value)}
                            placeholder="请输入联系电话">
                            <Text style={{fontSize:14,width:100}}>联系电话</Text>
                        </InputItem> */}

                        <TextInputItem
                            label={"联系电话"}
                            placeholder={"请输入联系电话"}
                            maxLength={50}
                            onlyNum={true}
                            value={userInfoVo.contactPhone}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{contactPhone:value})
                                this.setState({
                                    contactPhone:data
                                })
                                this._changeFormData('contactPhone',value)
                            }}
                        />
                        {/* <InputItem
                            value={userInfoVo.contactEmail}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('contactEmail',value)}
                            placeholder="请输入电子邮箱">
                            <Text style={{fontSize:14,width:100}}>电子邮箱</Text>
                        </InputItem> */}

                        <TextInputItem
                            label={"电子邮箱"}
                            placeholder={"请输入电子邮箱"}
                            maxLength={50}
                            onlyNum={true}
                            value={userInfoVo.contactEmail}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{contactEmail:value})
                                this.setState({
                                    contactEmail:data
                                })
                                this._changeFormData('contactEmail',value)
                            }}
                        />


                        {/* <InputItem
                            value={userInfoVo.contactAddress}
                            maxLength={100}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('contactAddress',value)}
                            placeholder="请输入联系地址">
                            <Text style={{fontSize:14,width:100}}>联系地址</Text>
                            
                        </InputItem> */}

                        <TextInputItem
                            label={"联系地址"}
                            placeholder={"请输入联系地址"}
                            maxLength={50}
                            value={userInfoVo.contactAddress}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{contactAddress:value})
                                this.setState({
                                    contactAddress:data
                                })
                                this._changeFormData('contactAddress',value)
                            }}
                        />

                        {/* <InputItem
                            value={userInfoVo.unitName}
                            maxLength={50}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('unitName',value)}
                            placeholder="请输入单位名称">
                            <Text style={{fontSize:14,width:100}}>单位名称</Text>
                        </InputItem> */}

                        <TextInputItem
                            label={"单位名称"}
                            placeholder={"请输入单位名称"}
                            maxLength={50}
                            value={userInfoVo.unitName}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{unitName:value})
                                this.setState({
                                    unitName:data
                                })
                                this._changeFormData('unitName',value)
                            }}
                        />

                        {/* <InputItem
                            value={userInfoVo.position}
                            maxLength={50}
                            labelNumber={6}
                            onChange={(value) => this._changeFormData('position',value)}
                            placeholder="请输入职务">
                            <Text style={{fontSize:14,width:100}}>职务</Text>
                        </InputItem> */}

                        <TextInputItem
                            label={"职务"}
                            placeholder={"请输入职务"}
                            maxLength={50}
                            value={userInfoVo.position}
                            labelWidth={100}
                            onChange={(value)=>{
                                let data=Object.assign({},this.state.userInfoVo,{position:value})
                                this.setState({
                                    position:data
                                })
                                this._changeFormData('position',value)
                            }}
                        />

                    </List>
                </ScrollView>
                <PickerViewModalCas
                    ref={'typePicker'}
                    colsNum={1}
                    data={this.state.idTypeDict}
                    title={'证件类型'}
                    onChoose={(data) => {
                        // this.setState({selectedPickData: data});
                        this._changeFormData('contactIdType',data, 'select');
                        this.refs.typePicker.hidden();
                    }}
                />
                {this._renderPersonalDialog()}
            </View>
        );
    }
    onChoosePoint(item) {
        console.log(item)
        const data = {
            contactName: item.name,
            contactGender: item.gender+'',
            contactGenderLabel : '',
            contactIdType: item.idType,
            contactIdTypeLabel: item.idTypeLabel,
            contactIdNumber: item.idNumber,
            contactPhone:'',
            contactEmail: item.email,
            contactAddress:'',
            unitName:'',
            position: '',
            ...item,
        }

        this.setState({
            userInfoVo: data
        })
        this.props.onChange && this.props.onChange(data)
    }
    _renderPersonalDialog(){
        return (
            <PersonalDialog
                ref={dialog => this.personalDialog = dialog}
                onChoose={(item) => this.onChoosePoint(item)}
            />
        )
    }



    _renderHeaderBtns(){
        return (
            <View style={{flexDirection: 'row'}}>
                <TouchableOpacity
                    style={{flex: 1,marginRight: 5}}
                    onPress={()=>this.personalDialog.show()}
                >
                    <Image source={require('../../../assets/images/report/report_check.png')} style={{width: '100%',height: 60}} />
                </TouchableOpacity>
                <TouchableOpacity style={{flex: 1,marginLeft: 5}}>
                    <Image source={require('../../../assets/images/report/report_dist.png')} style={{width: '100%',height: 60}} />
                </TouchableOpacity>
            </View>

        )
    }
    _renderHeaderBtns2(){
        return (
              <View style={{flexDirection: 'row'}}>
                    <TouchableOpacity style={{flex: 1,boxSizing:"border-box",}}
                          onPress={()=>this._BaiDuAi()}
                    >
                          <View style={{width: '80%',
                                      backgroundColor:'#479dff',
                                      borderRadius:4,
                                      padding:5,
                                      marginTop:10,
                                      marginRight:'auto',
                                      marginBottom:10,
                                      marginLeft:'auto'
                                      }}>
                            <Text style={styles.ImgBox}>身份证拍照识别</Text>
                          </View>
                    </TouchableOpacity>
              </View>


        )
    }
}

const styles = StyleSheet.create({
    ImgBox:{
        borderRadius:4,
        width:"100%",
        lineHeight:32,
        textAlign:'center',
        color:"#fff"
    },
    boxBorder:{
        marginBottom:4,
        marginLeft:4,
        marginRight:4,
        marginTop:4
    },


})
